package dbclient

import (
	"UbiOsCommCore/utils"
	"gopkg.in/yaml.v3"
	"os"
	"reflect"
	"strings"
)

type Yaml struct {
	path string
	Yaml map[string]interface{}
}

type Return[T any] struct {
	Value T
}

// 初始化DB 获取配置
func (y *Yaml) Init(path string) {
	//遍历当前文件夹 使用获取到的第一个符合条件的yml 或者指定的路径yml
	y.Yaml = y.ReadYamlAsMap(path)
	// 查询条件保存在一个json文件中

}

func (y *Yaml) ReadYamlAsMap(path string) map[string]interface{} {
	var resultMap = make(map[string]interface{})
	data, err := os.ReadFile(path)
	if err != nil {
		utils.Log.Fatal(err)
	}
	err = yaml.Unmarshal(data, resultMap)
	return resultMap
}

// get value of attrNames which split by .
func (y *Yaml) FindAttr(attrNames string) interface{} {
	var attrArr []string
	var tmpResult interface{}
	src := y.Yaml
	attrArr = strings.Split(attrNames, ".")
	for _, attr := range attrArr {
		tmpResult = src[attr]
		if tmpResult == nil {
			return nil
		}
		if reflect.TypeOf(tmpResult).Kind() == reflect.Map {
			src = tmpResult.(map[string]interface{})
		}
		//else if reflect.TypeOf(tmpResult).Kind() == reflect.String {
		//	return tmpResult.(string)
		//} else if reflect.TypeOf(tmpResult).Kind() == reflect.Int {
		//	return tmpResult.(int)
		//}
	}
	return tmpResult
}
